Binary Tree
A comprehensive guide to tree algorithms and techniques for Data Structures and Algorithms.
Table of Contents
- Basic Tree Node Structure
- Tree Traversal Techniques
- Tree Properties and Measurements
- Tree Search Techniques
- Path Finding Techniques
- Tree Modification Techniques
- Binary Search Tree Operations
- Advanced Tree Techniques
- Usage Examples
Basic Tree Node Structure
The foundation of all tree operations starts with a simple node structure:
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
Helper Function: Create Sample Tree
function createSampleTree() {
// 1
// / \
// 2 3
// / \ \
// 4 5 6
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
return root;
}
Tree Traversal Techniques
Tree traversal is fundamental to most tree operations. There are two main categories: Depth-First Search (DFS) and Breadth-First Search (BFS).
Depth-First Search (DFS) Traversals
1. Pre-order Traversal: Root → Left → Right
function preorderTraversal(root) {
const result = [];
function dfs(node) {
if (!node) return;
result.push(node.val); // Process root first
dfs(node.left); // Then left subtree
dfs(node.right); // Then right subtree
}
dfs(root);
return result;
}
Time Complexity: O(n) | Space Complexity: O(h) where h is height